package com.backend.controller.teacher;

import com.backend.common.constant.MessageConstant;
import com.backend.common.result.Result;
import com.backend.common.utils.AliOssUtil;
import com.backend.pojo.entity.CourseMaterial;
import com.backend.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/teacher/lesson")

@CrossOrigin
public class TeacherCourseController {

    @Autowired
    private AliOssUtil aliOssUtil;


    @Autowired
    private CourseService courseService;


    /**
     * 查询课程资料
     * @param courseMaterial
     * @return
     */
    @GetMapping
    public Result<List<CourseMaterial>> getAllCourseMaterial(@RequestBody  CourseMaterial courseMaterial){

        log.info("开始查询：{}" , courseMaterial);

        List<CourseMaterial> courseMaterials = courseService.CourseQuery(courseMaterial);

        return Result.success(courseMaterials);
    }

    /**
     * 文件上传
     * @param file
     * @return
     */

    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {

        log.info("文件上传: {}", file);
        //防止重名 文件覆盖，对原始文件进行重命名 用uuid

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取原始文件的后缀  dfdfdf.jpg  从最后的. 的位置 截到最后
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;

            // 文件请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            return Result.success(filePath);


        } catch (IOException e) {
            log.error("文件上传失败：{}", e);

        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }



    @PostMapping
    public Result add(@RequestBody  CourseMaterial courseMaterial){
        log.info("开始添加课程资料：{} " , courseMaterial);
        courseService.add(courseMaterial);
        return Result.success(courseMaterial);
    }

    @DeleteMapping
    public Result DeleteById(Integer id){
        log.info("开始删除课程资料: {}" , id );
        courseService.deleteById(id);
        return Result.success();
    }

    @PutMapping
    public Result Update(@RequestBody CourseMaterial courseMaterial){
        log.info("开始修改课程资料：{}" ,courseMaterial);
        courseService.update(courseMaterial);
        return Result.success();
    }

}
